package com.bcu.cn.onlineexamsystem.exammanage.controller;

import com.bcu.cn.onlineexamsystem.exammanage.entity.Exam;
import com.bcu.cn.onlineexamsystem.exammanage.entity.ExamForm;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Course;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Class;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Question;
import com.bcu.cn.onlineexamsystem.exammanage.entity.ExamReviewDTO;
import com.bcu.cn.onlineexamsystem.exammanage.entity.ReviewSubmitDTO;
import com.bcu.cn.onlineexamsystem.exammanage.service.ExamService;
import com.bcu.cn.onlineexamsystem.exammanage.service.CourseService;
import com.bcu.cn.onlineexamsystem.exammanage.service.ClassService;
import com.bcu.cn.onlineexamsystem.exammanage.service.QuestionService;
import com.bcu.cn.onlineexamsystem.exammanage.service.StudentExamService;
import com.bcu.cn.onlineexamsystem.exammanage.service.ExamReviewService;
import com.bcu.cn.onlineexamsystem.user.entity.User;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Controller
@RequestMapping("/exam")
public class ExamController {
    private static final Logger logger = LoggerFactory.getLogger(ExamController.class);

    @Autowired
    private ExamService examService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private ClassService classService;
    
    @Autowired
    private QuestionService questionService;

    @Autowired
    private StudentExamService studentExamService;

    @Autowired
    private ExamReviewService examReviewService;

    @GetMapping("/manage")
    public String examManage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("当前登录用户: {}", user);
        
        if (user == null) {
            logger.error("未获取到用户信息，请先登录");
            return "redirect:/login";
        }
        
        if (!"teacher".equals(user.getRole())) {
            logger.error("非教师用户，无权访问");
            return "redirect:/login";
        }
        
        // 自动更新考试状态
        examService.autoEndExpiredExams();
        
        List<Exam> exams = examService.getExamsByTeacherId(user.getUserId());
        logger.info("查询到的考试数量: {}", exams.size());
        
        model.addAttribute("exams", exams);
        return "teacher/exam/manage";
    }
    
    @GetMapping("/create")
    public String createExamPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 进入创建考试页面 ===");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return "redirect:/login";
        }

        // 获取教师课程列表
        List<Course> courses = courseService.getCoursesByTeacherId(user.getUserId());
        logger.info("获取到的课程列表: {}", courses);
        model.addAttribute("courses", courses);

        // 获取教师班级列表
        List<Class> classes = classService.getClassesByTeacherId(user.getUserId());
        logger.info("获取到的班级列表: {}", classes);
        model.addAttribute("classes", classes);

        return "teacher/exam/create";
    }
    
    @PostMapping("/create")
    public String createExam(@ModelAttribute ExamForm examForm, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 开始创建考试 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("考试表单数据: {}", examForm);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return "redirect:/login";
        }
        
        try {
            // 创建考试
            Integer examId = examService.createExam(examForm, user.getUserId());
            
            redirectAttributes.addFlashAttribute("success", "考试创建成功！");
            return "redirect:/exam/manage";
        } catch (Exception e) {
            logger.error("创建考试失败", e);
            redirectAttributes.addFlashAttribute("error", "考试创建失败：" + e.getMessage());
            return "redirect:/exam/create";
        }
    }

    // 获取教师课程列表
    @GetMapping("/api/teacher/courses")
    @ResponseBody
    public List<Course> getTeacherCourses(HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 获取教师课程列表 ===");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return List.of();
        }

        List<Course> courses = courseService.getCoursesByTeacherId(user.getUserId());
        logger.info("获取到的课程列表: {}", courses);
        return courses;
    }

    // 获取教师班级列表
    @GetMapping("/api/teacher/classes")
    @ResponseBody
    public List<Class> getTeacherClasses(HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 获取教师班级列表 ===");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return List.of();
        }
        
        List<Class> classes = classService.getClassesByTeacherId(user.getUserId());
        logger.info("获取到的班级列表: {}", classes);
        return classes;
    }

    // 获取试题列表
    @GetMapping("/api/questions")
    @ResponseBody
    public List<Question> getQuestions(@RequestParam String courseId, 
                                     @RequestParam(required = false) String type,
                                     HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 获取试题列表 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("课程ID: {}, 试题类型: {}", courseId, type);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return List.of();
        }
        
        List<Question> questions = questionService.getQuestionsByCourseId(courseId, type);
        logger.info("获取到的试题列表: {}", questions);
        return questions;
    }

    @DeleteMapping("/{examId}")
    @ResponseBody
    public Map<String, Object> deleteExam(@PathVariable String examId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 删除考试 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("考试ID: {}", examId);
        
        Map<String, Object> response = new HashMap<>();
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            response.put("success", false);
            response.put("message", "无权限执行此操作");
            return response;
        }
        
        try {
            boolean result = examService.deleteExam(examId);
            response.put("success", result);
            response.put("message", result ? "考试删除成功" : "考试删除失败");
        } catch (Exception e) {
            logger.error("删除考试失败", e);
            response.put("success", false);
            response.put("message", "删除考试失败：" + e.getMessage());
        }
        
        return response;
    }

    @PostMapping("/{examId}/publish")
    @ResponseBody
    public Map<String, Object> publishExam(@PathVariable String examId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 发布考试 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("考试ID: {}", examId);
        
        Map<String, Object> response = new HashMap<>();
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            response.put("success", false);
            response.put("message", "无权限执行此操作");
            return response;
        }
        
        try {
            boolean result = examService.publishExam(examId);
            response.put("success", result);
            response.put("message", result ? "考试发布成功" : "考试发布失败");
        } catch (Exception e) {
            logger.error("发布考试失败", e);
            response.put("success", false);
            response.put("message", "发布考试失败：" + e.getMessage());
        }
        
        return response;
    }

    @GetMapping("/{examId}")
    public String examDetail(@PathVariable String examId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 查看考试详情 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("考试ID: {}", examId);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return "redirect:/login";
        }
        
        try {
            Map<String, Object> detail = examService.getExamDetail(examId);
            model.addAllAttributes(detail);
            return "teacher/exam/detail";
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            return "redirect:/exam/manage";
        }
    }

    // 待批改考试列表页面
    @GetMapping("/pending")
    public String pendingExams(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 进入待批改考试列表页面 ===");
        logger.info("当前登录用户: {}", user);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return "redirect:/login";
        }
        
        List<ExamReviewDTO> pendingExams = examReviewService.getPendingExams(user.getUserId());
        logger.info("待批改考试数量: {}", pendingExams.size());
        
        model.addAttribute("pendingExams", pendingExams);
        return "teacher/exam/pending";
    }
    
    // 考试批阅详情页面
    @GetMapping("/review/{recordId}")
    public String examReview(@PathVariable Long recordId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 进入考试批阅页面 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("考试记录ID: {}", recordId);
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            return "redirect:/login";
        }
        
        try {
            // 先检查该考试是否属于当前教师
            ExamReviewDTO examReview = examReviewService.getExamReviewDetail(recordId, user.getUserId());
            
            model.addAttribute("examReview", examReview);
            return "teacher/exam/review";
        } catch (Exception e) {
            logger.error("获取考试批阅详情失败", e);
            return "redirect:/exam/pending";
        }
    }
    
    // 提交批阅结果
    @PostMapping("/review/submit")
    @ResponseBody
    public Map<String, Object> submitReview(@RequestBody ReviewSubmitDTO reviewSubmitDTO, HttpSession session) {
        User user = (User) session.getAttribute("user");
        logger.info("=== 提交批阅结果 ===");
        logger.info("当前登录用户: {}", user);
        logger.info("批阅数据: {}", reviewSubmitDTO);
        
        Map<String, Object> response = new HashMap<>();
        
        if (user == null || !"teacher".equals(user.getRole())) {
            logger.error("用户未登录或非教师用户");
            response.put("success", false);
            response.put("message", "无权限执行此操作");
            return response;
        }
        
        try {
            examReviewService.submitReview(reviewSubmitDTO);
            response.put("success", true);
            response.put("message", "批阅完成");
        } catch (Exception e) {
            logger.error("提交批阅结果失败", e);
            response.put("success", false);
            response.put("message", "批阅失败：" + e.getMessage());
        }
        
        return response;
    }

    // 新增：考试题目答题统计接口
    @GetMapping("/api/question-stat/{examId}")
    @ResponseBody
    public ResponseEntity<?> getExamQuestionStat(@PathVariable String examId) {
        try {
            return ResponseEntity.ok(examService.getExamQuestionStat(examId));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "msg", e.getMessage()));
        }
    }
} 